package com.v.air.app;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;

import com.v.air.app.bean.CityBean;
import com.v.air.app.tools.NetworkTool;

/**
 * 
 * @brief 整个应用程序Applicaiton
 * @author Fanhao.Yi
 * @date 2015年4月23日下午7:01:20
 * @version V1.0
 */
public class AppContext extends Application {
	private static CityBean cityBean = null;
	/** 对外提供整个应用生命周期的Context **/
	private static Context instance;
	/** 整个应用全局可访问数据集合 **/
	private static Map<String, Object> gloableData = new HashMap<String, Object>();

	/**
	 * 对外提供Application Context
	 * 
	 * @return
	 */
	public static Context gainContext() {
		return instance;
	}

	public void onCreate() {
		super.onCreate();
		instance = this;
		setCityBean(CityBean.getCityList().get(0));
		Thread.setDefaultUncaughtExceptionHandler(AppException
				.getAppExceptionHandler());

	}

	/**
	 * 获取网络是否已连接
	 * 
	 * @return
	 */
	public static boolean isNetworkReady() {
		return NetworkTool.getInstance().init(instance).isConnected();
	}

	public PackageInfo getPackageInfo() {
		PackageInfo info = null;
		try {
			info = getPackageManager().getPackageInfo(getPackageName(), 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace(System.err);
		}
		if (info == null)
			info = new PackageInfo();
		return info;
	}

	/******************************************************* Application数据操作API（开始） ********************************************************/

	/**
	 * 往Application放置数据（最大不允许超过5个）
	 * 
	 * @param strKey
	 *            存放属性Key
	 * @param strValue
	 *            数据对象
	 */
	public static void assignData(String strKey, Object strValue) {
		if (gloableData.size() > 5) {
			throw new RuntimeException("超过允许最大数");
		}
		gloableData.put(strKey, strValue);
	}

	/**
	 * 从Applcaiton中取数据
	 * 
	 * @param strKey
	 *            存放数据Key
	 * @return 对应Key的数据对象
	 */
	public static Object gainData(String strKey) {
		return gloableData.get(strKey);
	}

	/*
	 * 从Application中移除数据
	 */
	public static void removeData(String key) {
		if (gloableData.containsKey(key))
			gloableData.remove(key);
	}

	/******************************************************* Application数据缓存 ********************************************************/
	public boolean isReadDataCache(String cachefile) {
		return readObject(cachefile) != null;
	}

	private boolean isExistDataCache(String cachefile) {
		boolean exist = false;
		File data = getFileStreamPath(cachefile);
		if (data.exists())
			exist = true;
		return exist;
	}

	public boolean saveObject(Serializable ser, String file) {
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;
		try {
			fos = openFileOutput(file, MODE_PRIVATE);
			oos = new ObjectOutputStream(fos);
			oos.writeObject(ser);
			oos.flush();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				oos.close();
			} catch (Exception e) {
			}
			try {
				fos.close();
			} catch (Exception e) {
			}
		}
	}

	public Serializable readObject(String file) {
		if (!isExistDataCache(file)) {
			return null;
		}
		FileInputStream fis = null;
		ObjectInputStream ois = null;
		try {
			fis = openFileInput(file);
			ois = new ObjectInputStream(fis);
			return (Serializable) ois.readObject();
		} catch (FileNotFoundException e) {
		} catch (Exception e) {
			e.printStackTrace();

			if (e instanceof InvalidClassException) {
				File data = getFileStreamPath(file);
				data.delete();
			}
		} finally {
			try {
				ois.close();
			} catch (Exception e) {
			}
			try {
				fis.close();
			} catch (Exception e) {
			}
		}
		return null;
	}

	public void deleteObject(String file) {
		if (!isExistDataCache(file)) {
			return;
		}
		File data = getFileStreamPath(file);
		data.delete();
	}

	public CityBean getCityBean() {
		return cityBean;
	}

	public void setCityBean(CityBean cityBean) {
		AppContext.cityBean = cityBean;
	}

}
